import tkinter as tk
from tkinter import messagebox
import pymysql

from bank01.Simulate import BankSimulator

# 连接数据库
db = pymysql.connect(
    host='1.94.52.166',
    user='root',
    password='123456',
    database='bank'
)
cursor = db.cursor()

# 用户类
class User:
    def __init__(self, username, password, balance=0, loan=0, is_active=True):
        self.username = username
        self.password = password
        self.balance = balance
        self.loan = loan
        self.is_active = is_active

    def deposit(self, amount):
        self.balance += amount
        self.update_db()

    def withdraw(self, amount):
        if amount > self.balance:
            return False
        else:
            self.balance -= amount
            self.update_db()
            return True

    def report_lost(self):
        self.is_active = False
        self.update_db()
    def apply_loan(self, amount):
        self.balance += amount
        self.loan += amount
        self.update_db()

    def repay_loan(self, amount):
        if amount > self.balance:
            return False
        else:
            self.balance -= amount
            self.loan -= amount
            if self.loan < 0:
                self.loan = 0
            self.update_db()
            return True

    def update_db(self):
        cursor.execute(
            "UPDATE users SET balance=%s, loan=%s, is_active=%s WHERE username=%s",
            (self.balance, self.loan, self.is_active, self.username)
        )
        db.commit()

# 银行管理系统类
class BankManagementSystem:
    def __init__(self, root):
        self.root = root
        self.root.title("银行管理系统")

        self.current_user = None

        self.main_screen()

    def main_screen(self):
        self.clear_screen()

        tk.Label(self.root, text="欢迎使用银行管理系统", font=("Arial", 16)).pack()
        tk.Button(self.root, text="登录", command=self.login_screen).pack(pady=10)
        tk.Button(self.root, text="注册", command=self.register_screen).pack(pady=10)

    def clear_screen(self):
        for widget in self.root.winfo_children():
            widget.destroy()

    def register_screen(self):
        self.clear_screen()

        tk.Label(self.root, text="注册新账户", font=("Arial", 16)).pack(pady=10)

        tk.Label(self.root, text="用户名:").pack()
        username_entry = tk.Entry(self.root)
        username_entry.pack()

        tk.Label(self.root, text="密码:").pack()
        password_entry = tk.Entry(self.root, show="*")
        password_entry.pack()

        tk.Button(self.root, text="注册", command=lambda: self.register(username_entry.get(), password_entry.get())).pack(pady=10)
        tk.Button(self.root, text="返回", command=self.main_screen).pack(pady=10)

    def register(self, username, password):
        cursor.execute("SELECT * FROM users WHERE username=%s", (username,))
        result = cursor.fetchone()
        if result:
            messagebox.showerror("错误", "用户名已存在")
        else:
            cursor.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, password))
            db.commit()
            messagebox.showinfo("成功", "注册成功")
            self.main_screen()

    def login_screen(self):
        self.clear_screen()

        tk.Label(self.root, text="用户登录", font=("Arial", 16)).pack(pady=10)

        tk.Label(self.root, text="用户名:").pack()
        username_entry = tk.Entry(self.root)
        username_entry.pack()

        tk.Label(self.root, text="密码:").pack()
        password_entry = tk.Entry(self.root, show="*")
        password_entry.pack()

        tk.Button(self.root, text="登录", command=lambda: self.login(username_entry.get(), password_entry.get())).pack(pady=10)
        tk.Button(self.root, text="返回", command=self.main_screen).pack(pady=10)

    def login(self, username, password):
        cursor.execute("SELECT * FROM users WHERE username=%s AND password=%s", (username, password))
        result = cursor.fetchone()
        if result:
            if result[4]:  # 检查账户是否有效
                self.current_user = User(username, password, result[2], result[3], result[4])
                self.account_screen()
            else:
                messagebox.showerror("错误", "账户已挂失，无法登录")
        else:
            messagebox.showerror("错误", "用户名或密码错误")

    def account_screen(self):
        self.clear_screen()

        tk.Label(self.root, text=f"欢迎, {self.current_user.username}", font=("Arial", 16)).pack(pady=10)

        tk.Label(self.root, text=f"账户余额: ¥{self.current_user.balance}").pack(pady=10)
        tk.Label(self.root, text=f"贷款金额: ¥{self.current_user.loan}").pack(pady=10)

        # Create frames for rows
        row1 = tk.Frame(self.root)
        row2 = tk.Frame(self.root)
        row3 = tk.Frame(self.root)

        # Pack frames
        row1.pack(pady=5)
        row2.pack(pady=5)
        row3.pack(pady=5)

        # Add buttons to the frames
        tk.Button(row1, text="存款", command=self.deposit_screen).pack(side=tk.LEFT, padx=10)
        tk.Button(row1, text="取款", command=self.withdraw_screen).pack(side=tk.LEFT, padx=10)

        tk.Button(row2, text="挂失", command=self.report_lost_screen).pack(side=tk.LEFT, padx=10)
        tk.Button(row2, text="贷款", command=self.loan_screen).pack(side=tk.LEFT, padx=10)

        tk.Button(row3, text="还贷", command=self.repay_loan_screen).pack(side=tk.LEFT, padx=10)

        tk.Button(row3, text="模拟", command=self.startSim).pack(side=tk.LEFT, padx=10)

        tk.Button(root, text="退出", command=self.logout).pack(side=tk.LEFT, padx=10)
    def startSim(self):
        bank_simulator = BankSimulator()
        bank_simulator.root.mainloop()

    def deposit_screen(self):
        self.clear_screen()

        tk.Label(self.root, text="存款", font=("Arial", 16)).pack(pady=10)

        tk.Label(self.root, text="存款金额:").pack()
        amount_entry = tk.Entry(self.root)
        amount_entry.pack()

        tk.Button(self.root, text="确认", command=lambda: self.deposit(amount_entry.get())).pack(pady=10)
        tk.Button(self.root, text="返回", command=self.account_screen).pack(pady=10)

    def deposit(self, amount):
        try:
            amount = float(amount)
            self.current_user.deposit(amount)
            messagebox.showinfo("成功", f"存款成功，新余额为: ¥{self.current_user.balance}")
            self.account_screen()
        except ValueError:
            messagebox.showerror("错误", "请输入有效的金额")

    def withdraw_screen(self):
        self.clear_screen()

        tk.Label(self.root, text="取款", font=("Arial", 16)).pack(pady=10)

        tk.Label(self.root, text="取款金额:").pack()
        amount_entry = tk.Entry(self.root)
        amount_entry.pack()

        tk.Button(self.root, text="确认", command=lambda: self.withdraw(amount_entry.get())).pack(pady=10)
        tk.Button(self.root, text="返回", command=self.account_screen).pack(pady=10)

    def withdraw(self, amount):
        try:
            amount = float(amount)
            if self.current_user.withdraw(amount):
                messagebox.showinfo("成功", f"取款成功，新余额为: ¥{self.current_user.balance}")
            else:
                messagebox.showerror("错误", "余额不足")
            self.account_screen()
        except ValueError:
            messagebox.showerror("错误", "请输入有效的金额")

    def report_lost_screen(self):
        self.clear_screen()

        tk.Label(self.root, text="挂失账户", font=("Arial", 16)).pack(pady=10)
        tk.Label(self.root, text="确定要挂失此账户吗？").pack(pady=10)

        tk.Button(self.root, text="确认", command=self.report_lost).pack(pady=10)
        tk.Button(self.root, text="返回", command=self.account_screen).pack(pady=10)

    def report_lost(self):
        self.current_user.report_lost()
        messagebox.showinfo("成功", "账户已挂失")
        self.logout()

    def repay_loan_screen(self):
        self.clear_screen()

        tk.Label(self.root, text="还贷", font=("Arial", 16)).pack(pady=10)

        tk.Label(self.root, text="还款金额:").pack()
        amount_entry = tk.Entry(self.root)
        amount_entry.pack()

        tk.Button(self.root, text="确认", command=lambda: self.repay_loan(amount_entry.get())).pack(pady=10)
        tk.Button(self.root, text="返回", command=self.account_screen).pack(pady=10)

    def repay_loan(self, amount):
        try:
            amount = float(amount)
            if self.current_user.repay_loan(amount):
                messagebox.showinfo("成功", f"还贷成功，新余额为: ¥{self.current_user.balance}，剩余贷款: ¥{self.current_user.loan}")
            else:
                messagebox.showerror("错误", "余额不足")
            self.account_screen()
        except ValueError:
            messagebox.showerror("错误", "请输入有效的金额")

    def logout(self):
        self.current_user = None
        self.main_screen()

    def loan_screen(self):
        self.clear_screen()

        tk.Label(self.root, text="贷款", font=("Arial", 16)).pack(pady=10)

        tk.Label(self.root, text="贷款金额:").pack()
        amount_entry = tk.Entry(self.root)
        amount_entry.pack()

        tk.Button(self.root, text="确认", command=lambda: self.loan(amount_entry.get())).pack(pady=10)
        tk.Button(self.root, text="返回", command=self.account_screen).pack(pady=10)

    def loan(self, amount):
        try:
            amount = float(amount)
            self.current_user.apply_loan(amount)
            messagebox.showinfo("成功", f"贷款款成功，新余额为: ¥{self.current_user.balance}")
            self.account_screen()
        except ValueError:
            messagebox.showerror("错误", "请输入有效的金额")
# 主程序
if __name__ == "__main__":
    root = tk.Tk()
    app = BankManagementSystem(root)
    root.mainloop()
    # 关闭数据库连接
    db.close()
